import React, { useState, useEffect, useRef } from "react";
import { CloseCircleOutline, SearchOutline } from 'antd-mobile-icons';
import { CapsuleTabs, Slider } from "antd-mobile";
import { useNavigate } from "react-router-dom";
import { Popup } from 'antd-mobile';
import '../../css/zxx/Search.css';

function Search() {
    const navigate = useNavigate()
    const [xi, setXi] = useState([]);
    const [visible1, setVisible1] = useState(false);
    const [showIcons, setShowIcons] = useState(false);
    const [sehistory, setSehistory] = useState([
        { title: '摩托车修理' },
        { title: '粉刷墙壁' },
        { title: '水管维修' },
        { title: '窗户清洗' },
        { title: '搬家' },
        { title: '电脑维修' },
        { title: '洗衣服务' },
        { title: '地板清洗' }
    ]);
    const [searchContent, setSearchContent] = useState("");
    const [activeKey, setActiveKey] = useState('全部');
    const [priceRange, setPriceRange] = useState([0, 1000]);
    const [selectedRating, setSelectedRating] = useState('全部');

    const categories = ['全部', '清洁服务', '维修服务', '粉刷服务'];
    const ratings = ['全部', '5', '4', '3', '2'];

    const clearHistory = () => {
        setSehistory([]);
    };

    const deleteHistory = (index) => {
        const newHistory = sehistory.filter((_, i) => i !== index);
        setSehistory(newHistory);
    };

    const gl = (value) => {
        setXi([]);

        if (value) {
            sehistory.forEach((item) => {
                if (item.title.toLowerCase().includes(value.toLowerCase())) {
                    const regex = new RegExp(`(${value})`, "gi");
                    setXi((prev) => [
                        ...prev, 
                        { title: item.title.replace(regex,"<span style='color:purple'>$1</span>") }
                    ]);
                }
            });
        }
    };

    const handleSearchChange = (e) => {
        setSearchContent(e.target.value); 
        gl(e.target.value);
    };

    const handleKeyDown = (e) => {
        if (e.key === 'Enter' && searchContent.trim() !== '') {
            const newHistory = {
                title: searchContent,
            };
         
            if (!sehistory.some(item => item.title === newHistory.title)) {
                setSehistory([...sehistory, newHistory]); 
            }
            setSearchContent(''); 
        }
    };
    const handleFilterClick=()=>{
        console.log('被点击啦啦啦啦啦')
        setVisible1(true)
    }
    const inputRef = useRef(null)
    const ImgMonseDown = (e) => {
        e.preventDefault();
    }
    const tabss = [
        { key: '1', title: '全部' },
        { key: '2', title: '清洁服务' },
        { key: '3', title: '维修服务' },
        { key: '4', title: '粉刷服务' },
        { key: '5', title: '洗衣服务' },
    ];
    return (
        <>
            <div className="zx-searcharea" ref={inputRef}>
                <img src="../返回.png" alt="" className="zx-back" onClick={()=>{navigate(-1)}}/>
                <SearchOutline className="zx-search-icon" />
                <input
                    type="text"
                    placeholder='请输入内容'
                    className="zx-searchinp"
                    onFocus={() => setShowIcons(true)}
                    onBlur={() => setShowIcons(false)}
                    value={searchContent}
                    onChange={handleSearchChange}
                    onKeyDown={handleKeyDown}
                     
                />
                {showIcons && (
                    <div className="zx-clear-icon">
                        <div onClick={()=>{
                            handleFilterClick()
                            console.log(1);
                            
                        }}><img src="../czs_imgs/筛选.png" alt="" className="zx-clear-icon1" onMouseDown={ImgMonseDown} />
                        </div>
                        <CloseCircleOutline onClick={() => setSearchContent('')} />
                    </div>
                )}
            </div>
            <div>
                {xi.length > 0 ? (
                    xi.map((item, index) => {
                        return <p className="gltext" key={index} dangerouslySetInnerHTML={{ __html: item.title }}></p>;
                    })
                ) : (searchContent ? (
                    <div className="wujieguo">
                        <div className="serjie">
                            <p>搜索"<span>{searchContent}</span>"</p>
                            <span>0结果</span></div>
                        <img src="../czs_imgs/无结果.png" className="no-result"/>
                        <p className="no-result1">暂无结果</p>
                        <p className="no-result2">很抱歉，您输入的关键字找不到，请重新检查或使用其他关键字搜索。</p>
                    </div>
                ) : null)}
            </div>
            {xi.length > 0 || !searchContent ? (
                <>
                    <div className="zx-sea">
                        <p className="zx-seall1">搜索历史</p>
                        <p onClick={clearHistory} className="zx-seall">清除全部</p>
                    </div>
                    <div>
                        {sehistory.map((item, index) => (
                            <p key={index} className="zx-hissea">
                                {item.title}
                                <CloseCircleOutline 
                                    className="zx-cenhis" 
                                    onClick={() => deleteHistory(index)} 
                                />
                            </p>
                        ))}
                    </div>
                </>
            ) : null}

            <Popup
                visible={visible1}
                onMaskClick={() => setVisible1(false)}
                onClose={() => setVisible1(false)}
                bodyStyle={{ height: '70vh', padding: '16px' }}
            >
                <div className="filter-popup">
                    <h3 style={{textAlign: 'center', margin: '10px 0 20px'}}>筛选</h3>
                    
                    <div className="filter-section">
                        <h4>分类</h4>
                        <div className="category-tags">
                            {categories.map((category) => (
                                <span
                                    key={category}
                                    className={`category-tag ${activeKey === category ? 'active' : ''}`}
                                    onClick={() => setActiveKey(category)}
                                >
                                    {category}
                                </span>
                            ))}
                        </div>
                    </div>

                    <div className="filter-section">
                        <h4>价格</h4>
                        <Slider
                            range
                            value={priceRange}
                            onChange={setPriceRange}
                            min={0}
                            max={1000}
                            style={{
                                '--fill-color': '#8b5cf6',
                                '--track-background': '#e5e7eb',
                            }}
                        />
                        <div className="price-range">
                            <span>￥{priceRange[0]}</span>
                            <span>￥{priceRange[1]}</span>
                        </div>
                    </div>

                    <div className="filter-section">
                        <h4>评分</h4>
                        <div className="rating-tags">
                            {ratings.map((rating) => (
                                <span
                                    key={rating}
                                    className={`rating-tag ${selectedRating === rating ? 'active' : ''}`}
                                    onClick={() => setSelectedRating(rating)}
                                >
                                    {rating === '全部' ? rating : `${rating} ★`}
                                </span>
                            ))}
                        </div>
                    </div>

                    <div className="filter-actions">
                        <button className="reset-btn" onClick={() => {
                            setActiveKey('全部');
                            setPriceRange([0, 1000]);
                            setSelectedRating('全部');
                        }}>取消</button>
                        <button className="confirm-btn" onClick={() => {
                            setVisible1(false);
                        }}>确定</button>
                    </div>
                </div>
            </Popup>
        </>
    );
}

export default Search;    